import { BaseService as InfrastructureBaseService } from '../../infrastructure/base/BaseService';
import { DIContainer } from '../../infrastructure/di';

/**
 * 现代化Service基类
 * 继承基础架构的BaseService，添加业务相关功能
 * 职责：
 * 1. 继承基础生命周期管理
 * 2. 提供SDK访问和业务工具方法
 * 3. 统一错误处理和日志记录
 * 4. 支持依赖注入
 */
export abstract class ModernBaseService extends InfrastructureBaseService {
    protected container?: DIContainer;

    constructor(container?: DIContainer) {
        super();
        this.container = container;
    }

    /**
     * 获取SDK实例
     * 提供便捷的SDK访问方式
     * 使用延迟导入避免循环依赖
     */
    protected get sdk() {
        // 延迟导入避免循环依赖
        return require("../../core").default;
    }

    /**
     * 获取配置信息
     */
    protected get config() {
        return require("../../config").config;
    }

    /**
     * 获取配置键
     */
    protected get configKey() {
        return require("../../config").configKey;
    }

    /**
     * 获取游戏配置
     */
    protected get gameCfg() {
        return require("../../gameCfg").default;
    }

    /**
     * 获取依赖的服务
     * @param token 服务令牌
     * @returns 服务实例
     */
    protected getService<T>(token: string): T {
        if (!this.container) {
            throw new Error(`Container not available in ${this.serviceName}`);
        }
        return this.container.get<T>(token);
    }

    /**
     * 统一的业务错误处理
     * @param error 错误对象
     * @param operation 操作名称
     * @param context 上下文信息
     * @returns 标准错误响应
     */
    protected handleBusinessError(error: any, operation: string, context?: any): {
        success: false;
        message: string;
        error: string;
        operation: string;
        context?: any;
    } {
        this.log(`Business error in ${operation}: ${error.message}`, 'error');
        
        return {
            success: false,
            message: error.message || '操作失败',
            error: error.constructor.name || 'Unknown',
            operation,
            context
        };
    }

    /**
     * 创建成功响应
     * @param data 响应数据
     * @param message 成功消息
     * @returns 标准成功响应
     */
    protected createSuccessResponse<T>(data: T, message?: string): {
        success: true;
        data: T;
        message?: string;
        timestamp: Date;
    } {
        return {
            success: true,
            data,
            message,
            timestamp: new Date()
        };
    }

    /**
     * 创建失败响应
     * @param message 错误消息
     * @param error 错误详情
     * @returns 标准失败响应
     */
    protected createErrorResponse(message: string, error?: any): {
        success: false;
        message: string;
        error?: any;
        timestamp: Date;
    } {
        return {
            success: false,
            message,
            error,
            timestamp: new Date()
        };
    }

    /**
     * 验证必需参数
     * @param params 参数对象
     * @param requiredFields 必需字段列表
     * @throws 参数验证失败时抛出错误
     */
    protected validateRequiredParams(params: any, requiredFields: string[]): void {
        for (const field of requiredFields) {
            if (params[field] === undefined || params[field] === null) {
                throw new Error(`Missing required parameter: ${field}`);
            }
        }
    }

    /**
     * 安全执行异步操作
     * @param operation 操作函数
     * @param operationName 操作名称
     * @returns 操作结果
     */
    protected async safeExecute<T>(
        operation: () => Promise<T>,
        operationName: string
    ): Promise<{ success: boolean; data?: T; error?: string }> {
        try {
            this.ensureInitialized();
            this.log(`Starting operation: ${operationName}`);
            
            const result = await operation();
            
            this.log(`Operation completed successfully: ${operationName}`);
            return { success: true, data: result };
        } catch (error) {
            this.log(`Operation failed: ${operationName}, Error: ${(error as any).message}`, 'error');
            return { 
                success: false, 
                                error: (error as any).message || 'Unknown error'
            };
        }
    }

    /**
     * 批量处理操作
     * @param items 要处理的项目列表
     * @param processor 处理函数
     * @param operationName 操作名称
     * @returns 批量处理结果
     */
    protected async batchProcess<T, R>(
        items: T[],
        processor: (item: T, index: number) => Promise<R>,
        operationName: string
    ): Promise<{
        success: boolean;
        results: R[];
        errors: { index: number; item: T; error: string }[];
    }> {
        this.log(`Starting batch operation: ${operationName}, items: ${items.length}`);
        
        const results: R[] = [];
        const errors: { index: number; item: T; error: string }[] = [];

        for (let i = 0; i < items.length; i++) {
            try {
                const result = await processor(items[i], i);
                results.push(result);
            } catch (error) {
                errors.push({
                    index: i,
                    item: items[i],
                    error: (error as any).message || 'Unknown error'
                });
            }
        }

        const success = errors.length === 0;
        this.log(`Batch operation ${success ? 'completed' : 'completed with errors'}: ${operationName}`, 
                 success ? 'info' : 'warn');

        return { success, results, errors };
    }

    /**
     * 缓存操作结果
     * @param key 缓存键
     * @param operation 操作函数
     * @param ttl 缓存时间（毫秒）
     * @returns 缓存的结果
     */
    protected async cached<T>(
        key: string,
        operation: () => Promise<T>,
        ttl: number = 300000 // 5分钟默认
    ): Promise<T> {
        // 简单的内存缓存实现
        const cache = (this as any)._cache = (this as any)._cache || new Map();
        const cacheKey = `${this.serviceName}_${key}`;
        
        // 检查缓存
        const cached = cache.get(cacheKey);
        if (cached && (Date.now() - cached.timestamp) < ttl) {
            this.log(`Cache hit for key: ${cacheKey}`);
            return cached.data;
        }

        // 执行操作并缓存结果
        const result = await operation();
        cache.set(cacheKey, {
            data: result,
            timestamp: Date.now()
        });

        this.log(`Cache set for key: ${cacheKey}`);
        return result;
    }

    /**
     * 清理缓存
     * @param pattern 缓存键模式（可选）
     */
    protected clearCache(pattern?: string): void {
        const cache = (this as any)._cache;
        if (!cache) return;

        if (pattern) {
            const keys = Array.from(cache.keys()).filter((key) => 
                (key as string).includes(pattern)
            );
            keys.forEach(key => cache.delete(key));
            this.log(`Cleared cache entries matching pattern: ${pattern}`);
        } else {
            cache.clear();
            this.log('Cleared all cache entries');
        }
    }

    /**
     * 性能监控装饰器
     * @param operation 操作函数
     * @param operationName 操作名称
     * @returns 带性能监控的操作结果
     */
    protected async withPerformanceMonitoring<T>(
        operation: () => Promise<T>,
        operationName: string
    ): Promise<T> {
        const startTime = Date.now();
        const startMemory = process.memoryUsage();

        try {
            const result = await operation();
            const endTime = Date.now();
            const endMemory = process.memoryUsage();
            
            const duration = endTime - startTime;
            const memoryDiff = endMemory.heapUsed - startMemory.heapUsed;

            this.log(`Performance: ${operationName} took ${duration}ms, memory: ${memoryDiff} bytes`);
            
            return result;
        } catch (error) {
            const endTime = Date.now();
            const duration = endTime - startTime;
            this.log(`Performance: ${operationName} failed after ${duration}ms`, 'error');
            throw error;
        }
    }
}
